//已投vm
var doneVM = new Vue({
    el:"#app2",
    data: {
        id:'',
        advertiser_id: '',
        adType: '1',
        type:'',
        img:'',
        explan:'',
        isUpload:false,
        xhr:''
    },
    watch: {
        isUpload: function(n){
            if(!n){
                $("#uploadFileProgress").hide().children('div').css('width',0).text(0);
            }
        }
    },
    methods:{
        closeModal: function(){
            var that = this;
            if(that.isUpload){
                var n = noty({
                    text: '正在上传文件中，你确定要中断操作吗？',
                    type: 'confirm',
                    layout:'center',
                    modal:true,
                    buttons:[
                        {
                            addClass:'btn btn-cus-size-a btn-cus-gray',
                            text:'取消',
                            onClick: function($n){
                               n.close();
                            }
                        },
                        {
                            addClass:'btn btn-cus-size-a btn-cus-red',
                            text:'确定',                              
                            onClick:function($n){
                                that.xhr.abort();
                                $("#myModal2").modal('hide');
                                that.isUpload = false;
                            }
                        }
                    ]
                });
                return;
            }
            $("#myModal2").modal('hide');
        },
        done: function(e){
            var that = this,flagPonit =true;
            if(e.target.disabled){
                return;
            }

             //先验证表单
            if(!that.img){
                //alert("请上传播出证明图片文件！");
                var n = noty({
                    text: "请上传有效的播出证明文件！",
                    type: 'error'
                });
                return;
            }

            // 已投提交需要确认 已选日期的每一天至少有一个时间点
            $.ajax({
                url:WEBCONF.basePath+"/bsqx/getShowtimeInfo",
                type:'post',
                data:{
                    adplan_id:this.id
                }
            }).done(function(res){
                var data = JSON.parse(res);
                if(data.rt==1 && data.con){
                    var conCur = data.con;
                    for(var i=0;i<conCur.length;i++){
                        if(!conCur[i]["showtime_info"]){
                            flagPonit = false;
                            break;
                        }
                    }

                    if(!flagPonit){ 
                        var n2 = noty({
                            text: '请先上传时间点！',
                            type: 'error'
                        });
                        return ;
                    }else{ // 判断每一天都必须有个时间点之后 在执行提交


                       

                        e.target.disabled = true;

                        var obj = new FormData();
                        if(that.img==='video' || that.img==='audio'){
                            obj.append('src',$("#imgFile")[0].files[0]);
                            mediaUpdate(obj).done(function(res){
                                that.isUpload = false;
                                res = JSON.parse(res);
                                if(!res.rt){
                                    //alert("图片上传失败！请重试~");
                                    var n = noty({
                                        text: "多媒体资源上传失败,请重试!",
                                        type: 'error'
                                    });
                                    e.target.disabled = false;
                                    return;
                                }
                                that.ajaxInfo(res,e.target);                    
                            }).fail(function(xhr){
                                var n = noty({
                                    text: '多媒体资源上传失败，网络出错！',
                                    type: 'error'
                                });
                                e.target.disabled = false;
                                that.isUpload = false;
                            });
                        }else{
                            obj.append('src',that.img);
                            imgUpdate(obj).done(function(res){
                                that.isUpload = false;
                                res = JSON.parse(res);
                                if(!res.rt){
                                    //alert("图片上传失败！请重试~");
                                    var n = noty({
                                        text: "图片上传失败,请重试!",
                                        type: 'error'
                                    });
                                    e.target.disabled = false;
                                    return;
                                }
                                that.ajaxInfo(res,e.target);
                                
                            });
                        }

                    }
                }
            })


            
        },
        ajaxInfo: function(res,el){
            var that = this;

            operateFMADPlan({
                explanation:that.explan,
                show_prove:res.des,
                adplan_id:that.id,
                advertiser_id: that.advertiser_id,
                plan_type:that.adType,
                
                user: $("#accountname").val(),
                status:3
            },function(res){
                res = JSON.parse(res);
                if(res.rt==1){
                    //alert("操作成功！");
                    var n = noty({
                        text: "操作成功！",
                        type: 'success',
                        callback:{
                            afterShow: function(){
                                setTimeout(function(){
                                    window.location.reload(true);
                                },1000);
                            }
                        }
                    });
                    
                }else{
                    //alert(res.des);
                    var n2 = noty({
                        text: res.des,
                        type: 'error'
                    });
                    el.disabled = false;
                }
            });
        }
    }
});


var appTimes = new Vue({
      el:"#app7",
      data:{
        medias:[],
        selday:0,

      },
      methods:{
        tabDay:function(i){
            this.selday = i;
        }
      },
      ready:function(){
        
      }
  });

//不通过vm
var rejectVM = new Vue({
    el:"#app3",
    data: {
        id:'',
        advertiser_id: '',
        type:'',
        reson:'',
        material:'',
        reMedia:[],
        reject_media:[]
    },
    methods: {
        reject: function(){
            //先验证表单
            if(!this.reson){
                //alert("请填写有效的回拒说明！");
                var n = noty({
                    text: '请填写有效的回拒说明！',
                    type: 'error'
                });
                return;
            }
            
            var adPlanID = 1111,plan_type=0;

            if(this.reMedia.length<1){
                var n = noty({
                    text: '至少选择一个媒体不通过',
                    type: 'error'
                });
                return;
            }

            //if(this.reMedia.length>=1){
                var rejectMedia = this.$data.reject_media,rejectDescri = [];//获取已经勾选审核不通过的媒体名称
                if(this.reMedia.length == this.reject_media.length){ // 素材通过所有媒体不通过
                    plan_type=0;
                    adPlanID = this.id;

                    
                    for(var i =0;i<rejectMedia.length;i++){
                        rejectDescri.push(rejectMedia[i]["mediaName"]+'不通过');
                    }

                }else{ //部分媒体通过
                    plan_type=1;
                    adPlanID = this.reMedia.join(',');
                    for(var i =0;i<rejectMedia.length;i++){
                        if(adPlanID.indexOf(rejectMedia[i]["subPlanId"])>-1){
                            rejectDescri.push(rejectMedia[i]["mediaName"]+'不通过'); 
                        }   
                    }
                }
            //}

            var material_des = '';
            if(this.$data.material*1){
                material_des= "素材审核不通过"
            }else{
                material_des= "素材审核通过"
            }

            //回拒广告计划
            operateFMADPlan({
                explanation:this.reson,
                adplan_id:adPlanID,
                advertiser_id: this.advertiser_id,
                plan_type:plan_type,
                media_des:rejectDescri.join(','),
                user: $("#accountname").val(),
                material_des:material_des,
                status:1
            },function(res){
                res = JSON.parse(res);
                if(res.rt==1){
                    //alert("操作成功！");
                    var n = noty({
                        text: "操作成功！",
                        type: 'success',
                        callback:{
                            afterShow: function(){
                                setTimeout(function(){
                                    window.location.reload(true);
                                },1000);
                            }
                        }
                    });
                    
                }else{
                    var n2 = noty({
                        text: res.des,
                        type: 'error'
                    });
                }
            });    
        }
    }
});

//查看原由vm
var failVM = new Vue({
    el:"#app4",
    data: {
        explanation:''
    }
});


//查看原由vm
var showTimeVM = new Vue({
    el:"#app6",
    data: {
        planId:'',
        mediaName:'',
        timelevel_name:'',
        media_id:'',
        post_times:'',
        day_length:'',
        timelevel_price:'',
        post_date:'',
        hourMinAry:'',
        sel_day_points:[],
        selPointsAry:[],
        allPoints:[],
        selday:0,
        selPoints:0

    },
    methods:{
        addBg:function(i){
            this.selday = i;
        },
        addPoints:function(obj){
            obj.flag = !obj.flag;
        },
        removePoints:function(obj){
            obj.flag = false;
        },
        saveTime:function(){
            console.log(showTimeVM.$data);
            var adplan_id = showTimeVM.$data.planId;
            var allPoints = showTimeVM.$data.allPoints;
            var post_info = [],flagPonit = true;
            for(var i=0;i<=allPoints.length;i++){
                var tmpObj = {}
               if(allPoints[i]){
                    tmpObj.post_date = allPoints[i]["date"],flagAry = [];
                    for(var j=0;j<allPoints[i]["times"].length;j++){
                        var flagcur = allPoints[i]["times"][j]["flag"];
                        if(flagcur){
                            flagAry.push(allPoints[i]["times"][j]["name"]);
                        }
                    }
                    tmpObj.post_time  = flagAry.join(',');
                    post_info.push(tmpObj)
               } 
            } 

            console.log(post_info);
            for(var k=0;k<post_info.length;k++){
                if(post_info[k]["post_time"]){
                     flagPonit = false;
                     break;
                }
            }

            if(flagPonit){
                var n = noty({
                    text: '请至少选择一个时间点！',
                    type: 'error'
                });
                return false;
            }

            post_info = JSON.stringify(post_info);
            $.ajax({
                type:"post",
                url:WEBCONF.basePath+"/bsqx/addShowtimeInfo",
                data:{
                    adplan_id:adplan_id,
                    post_info:post_info
                }
            }).done(function(data){
                var res = JSON.parse(data);
                if(res.rt == 1){
                    var n = noty({
                        text: '操作成功！',
                        type: 'success',
                        callback:{
                            afterShow: function(){
                                setTimeout(function(){
                                    n.close();
                                    window.location.reload(true)
                                },3000);
                            }
                        }
                    });

                    $("#myModal6").modal("hide");

                }else{
                    var n = noty({
                        text: '操作失败！',
                        type: 'error'
                    });
                }

            })
        }
    }
});




//广告计划vm
var vm = new Vue({
    el: "#app",
    data: {
        Status:   ["新建待审","审核不通过","审核通过","待确认投放","申诉中","申诉失败","申诉成功","交易成功","1","1","1","1","1","待投放","投放中"],
        status:   ["新建待审","审核不通过","审核通过","待确认投放","申诉中","申诉失败","申诉成功","交易成功","1","1","1","1","1","待投放","投放中"],
        datas: []
    },
    methods: {
        selectDate: function(item){
            var that =this;

            var maxST = '1970-01-01';
            var minET = '9999-12-30';
            var forbidDay = '';
            var checkDays = item.date.length?item.date.join(',').replace(/-/g,'/'):'';

            //调用日历
            YDdatePiker.show({
              currentDate:item.date[0],
              starttime:maxST,
              endtime:minET,
              disDays:forbidDay || '',
              checkDays:checkDays || '',
              disAll:true,
              prev: function(date){
                YDdatePiker.setMon(date);
              },
              next: function(date){
                YDdatePiker.setMon(date);
              },
              check: function(day,days,elm){
                return;          
              }
            });

            $('#myModal8').modal('show');
        },
        reject: function(i){
            var that = this;
            rejectVM.$data.id = this.datas[i].id;
            rejectVM.$data.advertiser_id = this.datas[i].advertiser_id; 
            rejectVM.$data.reject_media = mediaInfo(this.datas[i].datas);    
        
        },
        doneAll: function(obj){
        	$.ajax({
        		url: WEBCONF.basePath+'/bsqx/fmplanOperate',
        		type: 'post',
        		data: {
        			adplan_id: obj.id,
        			status: 3,
        			user: $("#accountname").val(),
        			media_id: $("#userid").val()
        		},
        		success: function(data){
        			data = JSON.parse(data);
        			if(data.rt == 1){
        				var n = noty({
        					text: '操作成功！',
                			type: 'success',
                			callback:{
                                afterShow: function(){
                                    setTimeout(function(){
                                        n.close();
                                    },3000);
                                }
                            }
        				});
        				obj.status = 3;
        			}else{
        				var n = noty({
        					text: '操作失败！',
                			type: 'error'
        				});
        			}
        		},
        		error: function(res){
        			var n = noty({
    					text: '操作失败！',
            			type: 'error'
    				});
        		}
        		
        	})
        },
        checkTimes: function(obj){

         // var that =  this.$data.datas[i];
          console.log(obj);
          var id = obj.id;
          $.ajax({
              type:"post",
              url:WEBCONF.basePath+'/bsqx/getShowtimeInfo',
              data:{
                 adplan_id:id
              }
          }).done(function(res){
              var data = JSON.parse(res);
              appTimes.$data.selday=0;
              if(data.rt==1 ){
                  appTimes.$data.medias = data.con;
              }else{
                  appTimes.$data.medias = [];
              }
          })
        },
        pass: function(i){
            //采用广告计划
            var that = this;
            operateFMADPlan({
                adplan_id:that.datas[i].id,
                advertiser_id:that.datas[i].advertiser_id,
                plan_type:0,
                if_force:0,
                user: $("#accountname").val(),
                status:2
            },function(res){
                res = JSON.parse(res);
                if(res.rt==1){
                    that.datas[i].status = 2;
                    var n = noty({
                        text: "操作成功！",
                        type: 'success',
                        callback:{
                            afterShow: function(){
                                setTimeout(function(){
                                     window.location.reload(true);
                                    n.close();
                                },3000);
                            }
                        }
                    });
                }else if(res.rt==2){//如果是2表示库存用完了！
                    var n2 = noty({
                        text: '当前广告计划所投放播出时段已存在审核过的其他广告，是否继续追加？',
                        type: 'confirm',
                        layout:'center',
                        modal:true,
                        buttons:[
                            {
                                addClass:'btn btn-cus-size-a btn-cus-gray',
                                text:'取消',
                                onClick: function($n){
                                    n2.close();
                                }
                            },
                            {
                                addClass:'btn btn-cus-size-a btn-cus-red',
                                text:'确定',                              
                                onClick:function($n){
                                   operateFMADPlan({
                                        adplan_id:that.datas[i].id,
                                        advertiser_id:that.datas[i].advertiser_id,
                                        plan_type:0,
                                        if_force:1,
                                        
                                        user: $("#accountname").val(),
                                        adplan_type:that.adtypeObj[that.datas[i].adType],
                                        status:2
                                    },function(rs){
                                        rs  = JSON.parse(rs);
                                        if(rs.rt){
                                            that.datas[i].status = 2;
                                            var n = noty({
                                                text: "操作成功！",
                                                type: 'success',
                                                callback:{
                                                    afterShow: function(){
                                                        setTimeout(function(){
                                                             window.location.reload(true);
                                                            n.close();
                                                        },3000);
                                                    }

                                                }
                                            });
                                        }else{
                                            //alert(rs.des);
                                            var n2 = noty({
                                                text: res.des,
                                                type: 'error'
                                            });
                                        }
                                    });
                                }
                            }
                        ]
                    });
                }else{
                    var n3 = noty({
                        text: res.des,
                        type: 'error'
                    });
                }
            });
        },
        done: function(obj){
            //已投广告计划
            var that = this,flagPonit = false;
            console.log(that);
            doneVM.$data.id = obj.id;
            doneVM.$data.advertiser_id =  obj.advertiser_id;
            doneVM.$data.adType = obj.media_id?1:0;

        
        },
        showTime:function(obj){

            window.hourMinAry = [];
            console.log(obj);
            showTimeVM.$data.mediaName = obj.media_name;
            showTimeVM.$data.timelevel_name = obj.timelevel_name;
            showTimeVM.$data.media_id = obj.media_id;
            showTimeVM.$data.post_times = obj.post_times;
            showTimeVM.$data.day_length = 7;
            showTimeVM.$data.post_date =obj.plan_postdate;
            showTimeVM.$data.timelevel_price = obj.bid_price;
            showTimeVM.$data.allPoints =[];
            showTimeVM.$data.planId = obj.id;
            window.tempAry = [],window.tempObj= {};

            //获取频率下的时段级别对应的播出时段
            $.ajax({
                type:'post',
                data:{
                    brocast_id:obj.media_id
                },
                url:WEBCONF.basePath+'/bsqx/getDurationInfo'
            }).done(function(data){
                var res = JSON.parse(data),timePointAry = [];
                if(res.con && res.rt==1){
                    for(var i=0;i<res.con.length;i++){
                        if(res.con[i]["timelevel_name"] == obj.timelevel_name){
                            timePointAry = res.con[i]["show_points"]
                            break;
                        }
                    }

                    var timePointAll= [],tpAry =[];
                    if(timePointAry && timePointAry.length>=1){
                        for(var j=0;j<timePointAry.length;j++){
                            timePointAll.push(timePointAry[j]["show_point"]);
                        }

                        //对时间段进行排序
                        timePointAll = timePointAll.sort(function(a,b){
                            return Date.parse('2016/01/01 '+a.split('-')[0]) - Date.parse('2016/01/01 '+b.split('-')[0])

                        });

                        for(var t=0;t<timePointAll.length;t++){
                            if(timePointAll[t].indexOf("-")>-1){
                                var timesAry = timePointAll[t].split('-');
                                hourMin(timesAry[0],timesAry[1])
                            }else{
                                tpAry = timePointAll[t]
                            }
                        }
                        // 获取时间段下面的所有时间点
                        hourMinAry = (tpAry.length>=1)? hourMinAry.concat(tpAry) : hourMinAry;
                        hourMinTimeAry = [],selPoints =[];



                        

                        // 遍历事件点并添加一个标识符flag区分是否选择
                        for(var m=0;m<hourMinAry.length;m++){
                            var TempHMAry = {}
                            TempHMAry.name = hourMinAry[m];
                            TempHMAry.flag = false;
                            hourMinTimeAry.push(TempHMAry)
                        }
                        hourMinTimeAry = JSON.stringify(hourMinTimeAry);


                        // 生成一个总的showTimeVM.$data.allPoints 对象
                        for(var n=0;n<showTimeVM.$data.post_date.length;n++){
                            var allPontsAry = {}
                            allPontsAry.date = showTimeVM.$data.post_date[n];
                            allPontsAry.times = JSON.parse(hourMinTimeAry);
                            showTimeVM.$data.allPoints.push(allPontsAry)
                        }

                        $.ajax({
                            type:"post",
                            url:WEBCONF.basePath+"/bsqx/getShowtimeInfo",
                            data:{
                               adplan_id:obj.id
                            }
                        }).done(function(res){
                            var data = JSON.parse(res)
                            if(data.rt==1  && data.con){
                                selPoints = data.con;
                                showTimeVM.$data.selday = 0;
                                showTimeVM.$data.allPoints =  synaData(selPoints,showTimeVM.$data.allPoints);
                            }
                        });

                        showTimeVM.$data.hourMinAry = hourMinAry;
                        $(".checkTimes-date li").eq(0).addClass("bg01");
                    }
                    
                }else{
                     showTimeVM.$data.hourMinAry = '';
                    $(".checkTimes-date li").eq(0).addClass("bg01");
                }

            });

            

        },
        fail: function(i){
            //未投广告计划
            var that = this;
            operateFMADPlan({
                adplan_id:that.datas[i].id,
                advertiser_id:that.datas[i].advertiser_id,
                plan_type:0,
                
                user: $("#accountname").val(),
                status:4
            },function(res){
                res = JSON.parse(res);
                if(res.rt){
                    that.datas[i].status = 4;
                    var n = noty({
                        text: "操作成功！",
                        type: 'success',
                        callback:{
                            afterShow: function(){
                                setTimeout(function(){
                                    n.close();
                                },3000);
                            }
                        }
                    });
                }else{
                    //alert(res.des);
                    var n2 = noty({
                        text: res.des,
                        type: 'error'
                    });
                }
            });
        },
        listen: function(i){
            //预听广告音频内容
            window.audioPlayer.src = this.datas[i].video;
            window.audioPlayer.play();
            //匹配一个文件名
            var name = this.datas[i].video.slice(this.datas[i].video.lastIndexOf('/')+1);
            $("#playerTitle").text(name);
        },
        dele: function(i){
            //删除广告计划
            deleteADPlan({
                adplan_id:this.datas[i].id,
                advertiser_id:this.datas[i].advertiser_id,
                
                user: $("#accountname").val(),
                delete_status:2
            }).done(function(res){
                res = JSON.parse(res);
                if(res.rt==1){
                    var n = noty({
                        text: "操作成功！",
                        type: 'success',
                        callback:{
                            afterShow: function(){
                                setTimeout(function(){
                                    window.location.reload(true);
                                },1000);
                            }
                        }
                    });
                }else{
                    var n2 = noty({
                        text: res.des,
                        type: 'error'
                    });
                }
            });
        },
        reson: function(i){
            //查看失败原由
            failVM.$data.explanation = this.datas[i].explanation;
        }
    },
    init: function(){
    }
});

pageInit();


/**
 * 已经选择的时间点同步到初始化的数据中
 */
function synaData(selData,data){
    for(var i=0;i<selData.length;i++){
        for(var j=0;j<data.length;j++){
            if(selData[i]["post_date"] == data[j]["date"]){
                var selPoints = selData[i]["showtime_info"],allPoints = data[j]["times"]
                if(selPoints && allPoints){
                    for(var m=0;m<selPoints.length;m++){
                        for(var n =0;n<allPoints.length;n++){
                            if(selPoints[m]["showtime"] == allPoints[n]["name"]){
                                allPoints[n]["flag"] = true;
                            }
                        }
                    } 
                }
                
            }
        }
    }

    return data;
}

// 不通过媒体数据过滤
function mediaInfo(obj){
    var data= [];
    for(var i =0;i<obj.length;i++){
        var tempObj={};
        tempObj.mediaName = obj[i].media_name;
        tempObj.subPlanId = obj[i].id;
        data.push(tempObj);
    }
    return data;
}

// 时间点切割
function hourMin(startH,endH){
    tempAry01 = [],tempAry02 = [],st='',et='',st01='',et01 ='';
    startH = "2013/01/01 "+startH;
    endH = "2013/01/01 "+endH;
    startMax = "2013/01/01 23:55";
    startMin = "2013/01/01 00:00"

    if(Date.parse(startH) < Date.parse(endH)){
        st = startH;
        et = endH;
        for(var i=Date.parse(st);i<=Date.parse(et);i+=300000){
            var h =new Date(i).getHours(),min =new Date(i).getMinutes();
            h= (h>=10) ? h:'0'+h;
            min= (min>=10) ? min:'0'+min;
            hourMinAry.push(h+':'+min);
        }
    }else{ //如果结束开始时间大于结束时间
        st = startH;
        et = startMax;
        st01 = startMin;
        et01 = endH;
        //0:00 到 结束时间
        for(var i=Date.parse(st01);i<=Date.parse(et01);i+=300000){
            var h =new Date(i).getHours(),min =new Date(i).getMinutes();
            h= (h>=10) ? h:'0'+h;
            min= (min>=10) ? min:'0'+min;
            hourMinAry.push(h+':'+min);
        }   
        //开始时间到23:55
        for(var i=Date.parse(st);i<=Date.parse(et);i+=300000){
            var h =new Date(i).getHours(),min =new Date(i).getMinutes();
            h= (h>=10) ? h:'0'+h;
            min= (min>=10) ? min:'0'+min;
            hourMinAry.push(h+':'+min);
        }
        
    }
    
    return hourMinAry;
}

//vm初始化回调函数
function vmInitCB(res){
    res = JSON.parse(res);
    if(res.rt){
        if(res.con){
            var arr=[],
                data = res.con,
                obj;
            for(var i=0,j=data.length;i<j;i++){
                obj = new ADPlanData(data[i]);
                arr.push(obj);
            }
            vm.$data.datas = arr;
        }else{
            vm.$data.datas = [];
        }
        renderPaginator(res);
    }else{
        // console.log(res);
        // alert(res.des);
        var n = noty({
            text: res.des,
            type: 'error'
        });
    }
}

//请求广告计划
function getADList(data,cb){
    $.ajax({
        url: WEBCONF.basePath+"/bsqx/getFmcadplanList",
        type: "POST",
        data: data
    }).done(function(res){
        cb(res);
    }).fail(function(err){
        commonError("请求广告计划:",err);
    });
}

//广告计划对象类
function ADPlanData(obj){    
    //var download = $("#ctx").val()+'/ServletDownload?filepath=';
	var download = $("#ctx").val() + '/bsqx/download?urlString=';

    this.id          = obj.adplan_id;
    this.adPlanName  = obj.adplan_name;
    this.company     = obj.advertiser_name;
    this.advertiser_id=obj.advertiser_id;
    this.status      = obj.adplan_status*1;
    this.videoDownload= download+obj.voice_url;
    this.video       = obj.voice_url;
    this.sum         = obj.sum_counts;
    this.explanation = obj.explanation;
    this.industry    = obj.industry;
    this.date        = obj.post_date;
    
    this.submit_time = obj.submit_time;


    //解析单个广告信息
    var arr = [];
    if(obj.resource_info){
        for(var i=0,j=obj.resource_info.length;i<j;i++){
            arr.push(new AD(obj.resource_info[i]));
        }
    }

    this.datas = arr;
    this.resource_num= arr.length;


}
//广告详情对象类
function AD(obj){
    var download = $("#ctx").val()+'/bsqx/download?urlString=';
    this.media_id = obj.frequency_id;
    this.media_name = obj.frequency_name;
    this.media_img = obj.frequency_logo;
    this.timelevel_name = obj.timelevel_name;
    this.bid_price = obj.bid_price;
    this.plan_counts = obj.plan_counts;
    this.id = obj.plan_id;
    this.status = obj.status;
    this.duration = obj.duration;
    this.post_times = obj.post_times;    
    this.plan_postdate = (obj.plan_postdate) ? (obj.plan_postdate.split(',')) : '';
    this.prove  = download+obj.show_prove;
    this.show_prove  = obj.show_prove;
    this.date = obj.plan_postdate?obj.plan_postdate.split(','):[];
}

//操作广告计划
function operateFMADPlan(data,cb){
    $.ajax({
        url:WEBCONF.basePath+'/bsqx/fmplanOperate',
        type: 'POST',
        data: data
    }).done(cb).fail(function(err){
        commonError("操作失败：",err);
    });
}
//删除广告计划
function deleteADPlan(data){
    return $.ajax({
        url:WEBCONF.basePath+'/adplan/deletePlanInfo',
        type:'POST',
        data:data
    }).fail(function(xhr){
        // alert("操作失败，网络错误！");
        // console.log(xhr);
        var n = noty({
            text: '操作失败，网络错误！',
            type: 'error'
        });
    });
}


//获取当前页面的查询条件对象
function getSearchObj(n){
    return {
        status:$(".adStatusBtn span.current").attr('value'),
        pageIndex:n===undefined?0:n
    };
}


//各表单控件查询事件绑定
function eventBind(){

    //广告计划状态
    $(".adStatusBtn span").on('click',function(){
        $(this).addClass('current').siblings('span').removeClass('current');
        getADList(getSearchObj(),vmInitCB);
    });

}

//页面初始化
function pageInit(){
    
    getADList({
        media_id: $("#userid").val(),
        frequency_id:-1,
        adplan_type: $("#adType").val(),
        industry: '',
        status:10,
        pageIndex:0
    },vmInitCB);
    
    //事件绑定
    eventBind();

}

//渲染分页
function renderPaginator(res){
    //console.log(res);
    $.jqPaginator('#pagination1>ul', {
        totalPages:res.totalPage || 1,
        visiblePages:3,
        currentPage:res.currentPage || 1,
        onPageChange: function (num, type) {
            getADList(getSearchObj(num-1),vmInitCB);
        }
    });
    
    var start = (res.currentPage-1)*res.perPage+1;
    var end = Math.min(res.currentPage*res.perPage,+res.count);
    var str='';
    if(res.totalPage){
       str = "第"+start+"到第"+end+"条记录，";
    }
    $("#pagination").text(str+"总共"+res.count+"条记录");
}


//音视频上传
function mediaUpdate(data){
    return $.ajax({
        url:WEBCONF.basePath+'/advertiser/mp3Upload',
        type:'POST',
        contentType:false,
        processData:false,
        header:{
            "Content-Type":"multipart/form-data"
        },
        xhr: function()
          {
            var xhr = new window.XMLHttpRequest();
            //Upload progress
            xhr.upload.addEventListener("progress", function(evt){
              if (evt.lengthComputable) {  
                var percentComplete = evt.loaded / evt.total;
                percentComplete = (percentComplete*100).toFixed(2)+'%';
                $("#uploadFileProgress").show().children('div').css('width',percentComplete).text(percentComplete);
              }
            }, false);
            xhr.addEventListener("abort", function(evt){
                var n = noty({
                    text: '已取消上传！',
                    type: 'success',
                    callback:{
                        afterShow: function(){
                            setTimeout(function(){
                                n.close();
                            },3000);
                        }
                    }
                });
            });
            doneVM.$data.xhr = xhr;
            doneVM.$data.isUpload = true;

            return xhr;
          },
        data:data
    });
}
//图片上传
function imgUpdate(data){
    return $.ajax({
        url:WEBCONF.basePath+'/advertiser/imgFileUpload',
        type:'POST',
        contentType:false,
        processData:false,
        header:{
            "Content-Type":"multipart/form-data"
        },
        data:data
    }).fail(function(xhr){
        var n = noty({
            text: '图片上传失败，网络出错！',
            type: 'error'
        });
    });
}
$("#imgFile").on("change",function(e){
    var that = this;
    var file = this.files[0];
    if(file){
        var type = file.type.match(/image\/|video\/|audio\//i);
        console.log(file.type,type);
        if(type){
            switch(type[0].toUpperCase()){
                case 'IMAGE/':
                    img2base64(this.files[0],function(res){
                        doneVM.$data.img = res;
                    });
                    break;
                case 'VIDEO/':
                    doneVM.$data.img = 'video';
                    break;
                default:
                    doneVM.$data.img = 'audio';
            }
        }else{
            doneVM.$data.img = '';
            var n = noty({
                text: '请选择图片、视频或者音频文件！',
                type: 'error'
            });
        }
    }else{
        doneVM.$data.img = '';
    }
    
});

//图片选择并base64
function img2base64(file,cb){
    /*if(file.size>1024*1024){
       //alert('文件大于1Mb');
       var n = noty({
            text: '文件大于1Mb',
            type: 'warning'
        });            
    }*/
    var reader = new FileReader();
    reader.onload = function(f){
        cb && cb(f.target.result);
    };
    reader.readAsDataURL(file);
}



//公共错误
function commonError(msg,err){
    //console.log(err);
    //alert(msg+"网络出错");
    var n = noty({
        text: msg+"网络出错",
        type: 'error'
    });
}


